<template>
    <div class="warehouse-disassembly-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.disassemblyNo" style="width: 240px; padding-right: 15px;" placeholder="请输入拆卸单号" />
            <el-select v-model="searchParams.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
                <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
            </el-select>
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getDisassemblyOrderList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建拆卸单</el-button>
        </div>

        <!-- 拆卸单表格 -->
        <el-table :data="disassemblyOrderList" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="拆卸单ID" width="120" align="center" />
            <el-table-column prop="disassemblyNo" label="拆卸单号" width="180" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
            <el-table-column prop="disassemblyDate" label="拆卸日期" width="150" align="center" />
            <el-table-column prop="status" label="拆卸状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
                <span v-if="scope.row.status == 1" style="color: blue;">进行中</span>
                <span v-if="scope.row.status == 2" style="color: green;">已完成</span>
                <span v-if="scope.row.status == 3" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="200" align="center" />
            <el-table-column label="操作" width="300px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewDisassemblyOrderDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)" v-if="scope.row.status !== 2">修改</el-button>
                <el-button type="success" plain @click="completeDisassembly(scope.row.id)" v-if="scope.row.status === 1">完成拆卸</el-button>
                <el-button type="danger" plain @click="handleDeleteDisassemblyOrder(scope.row.id)" v-if="scope.row.status === 0">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑拆卸单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑拆卸单' : '创建拆卸单'" width="900px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="disassemblyOrder" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="disassemblyForm">
                <el-form-item label="拆卸单号" prop="disassemblyNo" v-if="isEdit">
                    <el-input v-model="disassemblyOrder.disassemblyNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-select v-model="disassemblyOrder.warehouseId" placeholder="请选择仓库" clearable>
                        <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="拆卸日期" prop="disassemblyDate">
                    <el-date-picker v-model="disassemblyOrder.disassemblyDate" type="date" placeholder="请选择拆卸日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="拆卸状态" prop="status" v-if="isEdit">
                    <el-select v-model="disassemblyOrder.status" placeholder="请选择拆卸状态">
                        <el-option label="草稿" :value="0" />
                        <el-option label="进行中" :value="1" />
                        <el-option label="已完成" :value="2" />
                        <el-option label="已取消" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="disassemblyOrder.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>

                <!-- 商品明细管理 -->
                <el-form-item label="商品明细">
                    <div class="items-container">
                        <div class="items-header">
                            <h4>输入商品（被拆分的商品，库存增加）</h4>
                            <el-button type="primary" size="small" @click="addInputItem">添加输入商品</el-button>
                        </div>
                        <el-table :data="disassemblyOrder.items?.filter(item => item.type === 'INPUT') || []" style="width: 100%" stripe border="true">
                            <el-table-column label="序号" width="60px" #default="scope" align="center">
                                {{ scope.$index + 1 }}
                            </el-table-column>
                            <el-table-column label="产品名称" width="200px">
                                <template #default="scope">
                                    <div v-if="isEdit && scope.row.productId && scope.row.productName">
                                        <span>{{ scope.row.productName }}</span>
                                      <el-button type="text" size="small" @click="editProduct(scope.row, 'INPUT')" style="margin-left: 10px;">修改</el-button>
                                    </div>
                                    <el-select v-else v-model="scope.row.productId" placeholder="请选择产品" @change="onProductChange(scope.row, 'INPUT')">
                                        <el-option v-for="product in products" :key="product.id" :label="product.name" :value="product.id" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" width="150px">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :step="1" />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" width="150px">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remark" placeholder="备注" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100px" align="center">
                                <template #default="scope">
                                    <el-button type="danger" size="small" @click="removeItem(scope.$index, 'INPUT')">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="items-header" style="margin-top: 20px;">
                            <h4>输出商品（拆分后的商品，库存减少）</h4>
                            <el-button type="success" size="small" @click="addOutputItem">添加输出商品</el-button>
                        </div>
                        <el-table :data="disassemblyOrder.items?.filter(item => item.type === 'OUTPUT') || []" style="width: 100%" stripe border="true">
                            <el-table-column label="序号" width="60px" #default="scope" align="center">
                                {{ scope.$index + 1 }}
                            </el-table-column>
                            <el-table-column label="产品名称" width="200px">
                                <template #default="scope">
                                    <div v-if="isEdit && scope.row.productId && scope.row.productName">
                                        <span>{{ scope.row.productName }}</span>
                                      <el-button type="text" size="small" @click="editProduct(scope.row, 'OUTPUT')" style="margin-left: 10px;">修改</el-button>
                                    </div>
                                    <el-select v-else v-model="scope.row.productId" placeholder="请选择产品" @change="onProductChange(scope.row, 'OUTPUT')">
                                        <el-option v-for="product in products" :key="product.id" :label="product.name" :value="product.id" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" width="150px">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :step="1" />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" width="150px">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remark" placeholder="备注" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100px" align="center">
                                <template #default="scope">
                                    <el-button type="danger" size="small" @click="removeItem(scope.$index, 'OUTPUT')">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 拆卸单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="拆卸单详情" width="800px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentDisassemblyOrder" class="disassembly-detail">
                <div class="detail-header">
                    <p><span class="label">拆卸单号：</span>{{ currentDisassemblyOrder.disassemblyNo }}</p>
                    <p><span class="label">仓库名称：</span>{{ currentDisassemblyOrder.warehouseName }}</p>
                    <p><span class="label">拆卸日期：</span>{{ currentDisassemblyOrder.disassemblyDate }}</p>
                    <p><span class="label">拆卸状态：</span>
                        <span v-if="currentDisassemblyOrder.status == 0" style="color: gray;">草稿</span>
                        <span v-if="currentDisassemblyOrder.status == 1" style="color: blue;">进行中</span>
                        <span v-if="currentDisassemblyOrder.status == 2" style="color: green;">已完成</span>
                        <span v-if="currentDisassemblyOrder.status == 3" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">备注：</span>{{ currentDisassemblyOrder.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>输入商品明细（被拆分的商品，库存增加）</h3>
                    <el-table :data="currentDisassemblyOrder.items?.filter(item => item.type === 'INPUT') || []" style="width: 100%" stripe border="true">
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="remark" label="备注" width="120" align="center" />
                    </el-table>

                    <h3 style="margin-top: 20px;">输出商品明细（拆分后的商品，库存减少）</h3>
                    <el-table :data="currentDisassemblyOrder.items?.filter(item => item.type === 'OUTPUT') || []" style="width: 100%" stripe border="true">
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="remark" label="备注" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createDisassemblyOrder, getDisassemblyOrderPage, getDisassemblyOrderWithDetails, updateDisassemblyOrder, deleteDisassemblyOrder, completeDisassemblyOrder } from '@/api/warehouse/warehouse_disassembly';
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 拆卸单列表数据
const disassemblyOrderList = ref([]);

// 仓库列表数据（用于选择）
const warehouses = ref([]);

// 产品列表数据（用于选择）
const products = ref([]);

// 搜索参数
const searchParams = ref({
    disassemblyNo: '',
    warehouseId: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的拆卸单
const disassemblyOrder = ref({});
const currentDisassemblyOrder = ref(null);

// 统一解包工具
function unwrap(res) {
  return (res && res.data !== undefined) ? res.data : res;
}
function unwrapPageRecords(payload) {
  const data = unwrap(payload);
  if (data && Array.isArray(data.records)) {
    return { records: data.records, total: Number(data.total) || data.records.length };
  }
  if (Array.isArray(data)) {
    return { records: data, total: data.length };
  }
  return { records: [], total: 0 };
}

// 表单验证规则
const formRules = ref({
    warehouseId: [
        { required: true, message: '请选择仓库', trigger: 'blur' }
    ],
    disassemblyDate: [
        { required: true, message: '请选择拆卸日期', trigger: 'change' }
    ]
});

// 获取拆卸单列表
function getDisassemblyOrderList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        disassemblyNo: searchParams.value.disassemblyNo,
        warehouseId: searchParams.value.warehouseId,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getDisassemblyOrderPage(pageParams).then(res => {
        const page = unwrapPageRecords(res);
        disassemblyOrderList.value = page.records;
        pagination.value.total = page.total;
    }).catch(error => {
        ElMessage.error('获取拆卸单列表失败');
        console.error('获取拆卸单列表失败:', error);
    });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
    getWarehouseList().then(res => {
        const data = unwrap(res);
        warehouses.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
    }).catch(error => {
        ElMessage.error('获取仓库列表失败');
        console.error('获取仓库列表失败:', error);
    });
}

// 获取产品列表（用于选择）
function fetchProducts() {
    getProductList().then(res => {
        const data = unwrap(res);
        products.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
    }).catch(error => {
        ElMessage.error('获取产品列表失败');
        console.error('获取产品列表失败:', error);
    });
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        disassemblyNo: '',
        warehouseId: '',
        startDate: '',
        endDate: ''
    };
    getDisassemblyOrderList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getDisassemblyOrderList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getDisassemblyOrderList();
}

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    disassemblyOrder.value = {
        items: [],
        status: 0,
        disassemblyDate: new Date().toISOString().split('T')[0],
        warehouseId: null,
        remark: '',
        // 不设置 disassemblyNo，让后端自动生成
        disassemblyNo: undefined
    };
    dialogVisible.value = true;
    // 重置表单
    if (proxy.$refs.disassemblyForm) {
        proxy.$refs.disassemblyForm.resetFields();
    }
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    // 先显示对话框，避免用户等待
    dialogVisible.value = true;

    // 获取拆卸单的完整信息（包含商品明细）
    getDisassemblyOrderWithDetails(row.id).then(res => {
        const data = unwrap(res);
        if (data) {
            // 深拷贝数据，避免直接修改原数据
            disassemblyOrder.value = JSON.parse(JSON.stringify(data));
            if (!disassemblyOrder.value.items) {
                disassemblyOrder.value.items = [];
            }
            // 确保其他字段也有默认值
            if (!disassemblyOrder.value.remark) disassemblyOrder.value.remark = '';
        } else {
            // 如果获取失败，使用基础数据
            disassemblyOrder.value = JSON.parse(JSON.stringify(row));
            if (!disassemblyOrder.value.items) {
                disassemblyOrder.value.items = [];
            }
            if (!disassemblyOrder.value.remark) disassemblyOrder.value.remark = '';
            ElMessage.warning('获取商品明细失败，请刷新后重试');
        }
    }).catch(error => {
        // 如果获取失败，使用基础数据
        disassemblyOrder.value = JSON.parse(JSON.stringify(row));
        if (!disassemblyOrder.value.items) {
            disassemblyOrder.value.items = [];
        }
        if (!disassemblyOrder.value.remark) disassemblyOrder.value.remark = '';
        ElMessage.error('获取商品明细失败');
        console.error('获取商品明细失败:', error);
    });
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单
    if (proxy.$refs.disassemblyForm) {
        proxy.$refs.disassemblyForm.resetFields();
    }
    // 重置数据
    disassemblyOrder.value = {
        items: [],
        status: 0,
        disassemblyDate: new Date().toISOString().split('T')[0],
        warehouseId: null,
        remark: '',
        disassemblyNo: undefined
    };
}

// 添加输入商品
function addInputItem() {
    if (!disassemblyOrder.value.items) {
        disassemblyOrder.value.items = [];
    }
    disassemblyOrder.value.items.push({
        productId: null,
        productName: null,
        productCode: null,
        quantity: 1,
        type: 'INPUT',
        remark: ''
    });
}

// 添加输出商品
function addOutputItem() {
    if (!disassemblyOrder.value.items) {
        disassemblyOrder.value.items = [];
    }
    disassemblyOrder.value.items.push({
        productId: null,
        productName: null,
        productCode: null,
        quantity: 1,
        type: 'OUTPUT',
        remark: ''
    });
}

// 移除商品明细
function removeItem(index, type) {
    const items = disassemblyOrder.value.items.filter(item => item.type === type);
    const globalIndex = disassemblyOrder.value.items.findIndex(item => item === items[index]);
    if (globalIndex !== -1) {
        disassemblyOrder.value.items.splice(globalIndex, 1);
    }
    // 确保 items 数组存在
    if (!disassemblyOrder.value.items) {
        disassemblyOrder.value.items = [];
    }
}

// 产品选择变化处理
function onProductChange(item, type) {
    const product = products.value.find(p => p.id === item.productId);
    if (product) {
        item.productName = product.name;
        item.productCode = product.code;
        // 确保其他字段也有默认值
        if (!item.quantity) item.quantity = 1;
        if (!item.remark) item.remark = '';
    }
}

// 编辑产品（显示选择器）
function editProduct(item, type) {
    // 清除产品信息，显示选择器
    item.productId = null;
    item.productName = null;
    item.productCode = null;
    // 确保其他字段也有默认值
    if (!item.quantity) item.quantity = 1;
    if (!item.remark) item.remark = '';
}

// 取消编辑产品（恢复显示）
function cancelEditProduct(item) {
    // 这里可以添加逻辑来恢复之前的产品信息
    // 暂时简单处理，用户需要重新选择
}

// 提交表单
function submitForm() {
    // 验证商品明细
    if (!disassemblyOrder.value.items || disassemblyOrder.value.items.length === 0) {
        ElMessage.warning('请至少添加一个商品明细');
        return;
    }

    const inputItems = disassemblyOrder.value.items.filter(item => item.type === 'INPUT');
    const outputItems = disassemblyOrder.value.items.filter(item => item.type === 'OUTPUT');

    if (inputItems.length === 0) {
        ElMessage.warning('请至少添加一个输入商品');
        return;
    }

    if (outputItems.length === 0) {
        ElMessage.warning('请至少添加一个输出商品');
        return;
    }

    // 验证商品是否选择完整
    for (let item of disassemblyOrder.value.items) {
        if (!item.productId) {
            ElMessage.warning('请选择所有商品');
            return;
        }
        if (!item.quantity || item.quantity <= 0) {
            ElMessage.warning('请输入有效的商品数量');
            return;
        }
    }

    proxy.$refs.disassemblyForm.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 更新拆卸单 - 清理数据，保留必要的字段
                const updateData = { ...disassemblyOrder.value };
                // 确保只发送 warehouseId，不发送 warehouseName
                if (updateData.warehouseName) {
                    delete updateData.warehouseName;
                }

                // 清理商品明细，移除不需要的字段
                if (updateData.items && Array.isArray(updateData.items)) {
                    updateData.items = updateData.items.map(item => {
                        const cleanItem = { ...item };
                        // 对于新添加的商品，移除 id 字段
                        if (!item.id || item.id < 0) {
                            delete cleanItem.id;
                        }
                        return cleanItem;
                    });
                }

                // 确保日期格式正确
                if (updateData.disassemblyDate) {
                    updateData.disassemblyDate = updateData.disassemblyDate.split('T')[0];
                }

                // 验证必要字段
                if (!updateData.warehouseId) {
                    ElMessage.error('请选择仓库');
                    return;
                }
                if (!updateData.disassemblyDate) {
                    ElMessage.error('请选择拆卸日期');
                    return;
                }

                // 确保备注字段不为 undefined
                if (updateData.remark === undefined) {
                    updateData.remark = '';
                }

                // 确保 items 数组存在
                if (!updateData.items || !Array.isArray(updateData.items)) {
                    updateData.items = [];
                }

                console.log('更新拆卸单数据:', updateData);

                updateDisassemblyOrder(updateData).then(res => {
                    ElMessage.success('拆卸单更新成功');
                    handleDialogClose();
                    getDisassemblyOrderList();
                }).catch(error => {
                    ElMessage.error('拆卸单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                // 创建拆卸单 - 清理数据，移除不需要的字段
                const createData = { ...disassemblyOrder.value };
                // 移除 id 和 disassemblyNo，让后端自动生成
                delete createData.id;
                delete createData.disassemblyNo;
                // 确保只发送 warehouseId，不发送 warehouseName
                if (createData.warehouseName) {
                    delete createData.warehouseName;
                }

                // 清理商品明细，移除不需要的字段
                if (createData.items && Array.isArray(createData.items)) {
                    createData.items = createData.items.map(item => {
                        const cleanItem = { ...item };
                        // 移除 id 字段，让后端自动生成
                        delete cleanItem.id;
                        return cleanItem;
                    });
                }

                // 确保日期格式正确
                if (createData.disassemblyDate) {
                    createData.disassemblyDate = createData.disassemblyDate.split('T')[0];
                }

                // 确保状态字段正确
                createData.status = 0; // 草稿状态

                // 验证必要字段
                if (!createData.warehouseId) {
                    ElMessage.error('请选择仓库');
                    return;
                }
                if (!createData.disassemblyDate) {
                    ElMessage.error('请选择拆卸日期');
                    return;
                }

                // 确保备注字段不为 undefined
                if (createData.remark === undefined) {
                    createData.remark = '';
                }

                // 确保 items 数组存在
                if (!createData.items || !Array.isArray(createData.items)) {
                    createData.items = [];
                }

                console.log('创建拆卸单数据:', createData);

                createDisassemblyOrder(createData).then(res => {
                    ElMessage.success('拆卸单创建成功');
                    handleDialogClose();
                    getDisassemblyOrderList();
                }).catch(error => {
                    ElMessage.error('拆卸单创建失败');
                    console.error('创建失败:', error);
                });
            }
        } else {
            ElMessage.warning('请完善拆卸单信息并确保格式正确');
            return false;
        }
    });
}

// 查看拆卸单详情
function viewDisassemblyOrderDetails(id) {
    getDisassemblyOrderWithDetails(id).then(res => {
        const data = unwrap(res);
        if (data) {
            // 确保数据完整性
            if (!data.items) data.items = [];
            if (!data.remark) data.remark = '';
            currentDisassemblyOrder.value = data;
        } else {
            currentDisassemblyOrder.value = null;
        }
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取拆卸单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentDisassemblyOrder.value = null;
    // 确保数据被清理
    if (currentDisassemblyOrder.value) {
        currentDisassemblyOrder.value = null;
    }
}

// 完成拆卸
function completeDisassembly(id) {
    ElMessageBox.confirm(
        '确定要完成该拆卸单吗？完成后将自动调整库存。',
        '完成确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        completeDisassemblyOrder(id).then(res => {
            ElMessage.success('拆卸单已完成，库存已调整');
            getDisassemblyOrderList();
        }).catch(error => {
            ElMessage.error('完成拆卸单失败');
            console.error('完成失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消操作');
    });
}

// 删除拆卸单
function handleDeleteDisassemblyOrder(id) {
    ElMessageBox.confirm(
        '确定要删除该拆卸单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteDisassemblyOrder(id).then(res => {
            ElMessage.success('拆卸单删除成功');
            getDisassemblyOrderList();
        }).catch(error => {
            ElMessage.error('拆卸单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 页面加载时获取拆卸单列表、仓库列表和产品列表
onMounted(() => {
    getDisassemblyOrderList();
    fetchWarehouses();
    fetchProducts();
});
</script>

<style scoped>
.warehouse-disassembly-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.disassembly-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.items-container {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
}

.items-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.items-header h4 {
    margin: 0;
    color: #409eff;
}
</style>
